package com.example.demo.socket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.edu.demo.entity.UsersInfo;
import com.edu.demo.service.IUsersInfoService;
import com.edu.demo.socket.SocketUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/*
 *
 *   @Author: Sjy
 *   @Date: 2024/3/25-03-25-19:05
 *   用于建立长连接的类
 */
@Component
//定义此类是WS的服务器端
@ServerEndpoint("/private/chat/{userId}")
public class WebSocketServer {

    //ws一共有四种状态
    private static Map<String, SocketUserInfo> map = new HashMap<>();
    //利用静态变量只会实例一次
    private static IUsersInfoService iUsersInfoService;
    @Autowired
    public void setIUsersInfoService(IUsersInfoService iUsersInfoService){
        this.iUsersInfoService = iUsersInfoService;
    }

    /**
     * 连接建立成功时触发
     * @param session 当前会话
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId")String userId){
        //判断userId存在再删除
        /*if(map.containsKey(userId)){
            map.remove(userId);
        }*/
        UsersInfo usersInfo = iUsersInfoService.getById(userId);
        //在put放了一个对象SocketUserInfo 一个是这个人的昵称，一个是session
        SocketUserInfo socketUserInfo = new SocketUserInfo(usersInfo.getNickname(), session);
        map.put(userId, socketUserInfo);
        System.out.println(socketUserInfo.toString()+"成功的建立了连接");
    }
    /**
     * 连接关闭时触发
     */
    @OnClose
    public void onClose(@PathParam("userId")String userId){
        map.remove(userId);
    }
    /**
     * 收到客户端消息时触发
     * @param message
     */
    @OnMessage
    public void onMessage(String message,@PathParam("userId") String userId){
        //解析msg的json数据
        JSONObject jsonObject = JSONUtil.parseObj(message);
        String msg = jsonObject.getStr("msg");
        String id = jsonObject.getStr("id");

        Session session = map.get(id).getSession();


        UsersInfo usersInfo = iUsersInfoService.getById(userId);
        JSONObject obj = JSONUtil.createObj()
                .put("nickName",usersInfo.getNickname())
                .put("msg",msg);

        try {
            session.getBasicRemote().sendText(obj.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 发生错误时触发
     * @param error
     */
    @OnError
    public void onError(Throwable error,@PathParam("userId")String userId){
        map.remove(userId);
    }
}
